<template>
    <div class="category-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="searchForm" :inline="true" class="search-form">
                            <el-form-item label="中英文:">
                                <el-select 
                                    v-model="searchForm.language" 
                                    placeholder="请选择" 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="中文" value="zh" />
                                    <el-option label="英文" value="en" />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 新增分类按钮 -->
        <div class="add-section">
            <el-button type="primary" :icon="CirclePlusFilled" @click="handleAddCategory">新增分类</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <!-- <el-table-column prop="id" label="分类id" width="100" align="center" /> -->
                    <el-table-column prop="categoryName" label="分类名称" align="center"/>
                    <el-table-column prop="level" label="层级" align="center" />
                    <el-table-column prop="description" label="分类描述" align="center" />
                    <el-table-column prop="createTime" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatDateTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ pagination.total }}条记录,当前在第{{ pagination.current }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.current"
                        :page-size="pagination.size"
                        :total="pagination.total"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="prev, pager, next, jumper"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getProductCategoryPage, deleteProductCategory } from '@/api/product/category';
import { CirclePlusFilled } from '@element-plus/icons-vue';

// 定义数据类型
interface CategoryItem {
    id: string;
    categoryName: string;
    parentId: string;
    parentName: string;
    level: number;
    icon: string;
    description: string;
    isVisible: number;
    isVisibleName: string;
    createTime: string;
    updateTime: string;
    children: string[];
    i18nList: Array<{
        id: string;
        categoryId: string;
        language: string;
        categoryName: string;
        description: string;
    }>;
}

interface CategoryPageParams {
    pageNum: number;
    pageSize: number;
    language?: string;
}

const router = useRouter();

// 时间格式化函数
const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '-';
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

// 搜索表单
const searchForm = reactive({
    language: ''
});

// 表格数据
const loading = ref(false);
const tableData = ref<CategoryItem[]>([]);

// 分页数据
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
});

// 获取分类列表
const fetchCategoryList = async () => {
    try {
        loading.value = true;
        const params: CategoryPageParams = {
            pageNum: pagination.current,
            pageSize: pagination.size,
            language: searchForm.language || undefined
        };
        
        const response = await getProductCategoryPage(params);
        
        const responseData = response as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || [];
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0;
        } else {
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取分类列表失败';
            ElMessage.error(errorMsg);
            tableData.value = [];
            pagination.total = 0;
        }
    } catch (error) {
        console.error('获取分类列表失败:', error);
        ElMessage.error('获取分类列表失败');
    } finally {
        loading.value = false;
    }
};

// 搜索方法
const handleSearch = () => {
    pagination.current = 1;
    fetchCategoryList();
};

// 重置搜索
const handleReset = () => {
    searchForm.language = '';
    pagination.current = 1;
    fetchCategoryList();
};

// 分页方法
const handlePageChange = (page: number) => {
    pagination.current = page;
    fetchCategoryList();
};

const handleSizeChange = (size: number) => {
    pagination.size = size;
    pagination.current = 1;
    fetchCategoryList();
};

// 新增分类
const handleAddCategory = () => {
    router.push('/product-category-form');
};

// 编辑分类
const handleEdit = (row: CategoryItem) => {
    router.push(`/product-category-form/${row.id}`);
};

// 删除分类
const handleDelete = async (row: CategoryItem) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除分类 "${row.categoryName}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        const response = await deleteProductCategory(row.id);
        const responseData = response as any;
        
        if (responseData && responseData.code === 200) {
            ElMessage.success('删除成功');
            // 重新加载列表
            fetchCategoryList();
        } else {
            ElMessage.error(response.data?.message || '删除失败');
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消删除');
        } else {
            console.error('删除分类失败:', error);
            ElMessage.error('删除失败');
        }
    }
};

// 页面初始化
onMounted(() => {
    // 加载初始数据
    fetchCategoryList();
});
</script>

<style scoped>
.category-list-container {
    padding: 20px;
}

/* 搜索区域 */
.search-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.search-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 新增按钮区域 */
.add-section {
    margin-bottom: 20px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

/* 分页区域 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    gap: 20px;
    align-items: center;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .category-list-container {
        padding: 10px;
    }
    
    .search-content {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }
    
    .search-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
    
    .pagination-content {
        flex-direction: column;
        gap: 15px;
        align-items: center;
    }
}
</style>
